package cn.information.view.SR;

import cn.information.view.MainUI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class SrSraverageUI extends JFrame {
    private static final String URL = "jdbc:mysql://localhost:3306/fp?useUnicode=true&characterEncoding=utf-8";
    private static final String USER = "root";
    private static final String PASSWORD = "ljw20040915.";

    // 月份输入框
    private JTextField monthInputField;

    public SrSraverageUI() {
        setTitle("月收入统计");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 添加月份输入框
        JLabel monthLabel = new JLabel("请输入月份 (XXXX-XX):");
        monthInputField = new JTextField(10);
        JPanel inputPanel = new JPanel();
        inputPanel.add(monthLabel);
        inputPanel.add(monthInputField);

        // 创建按钮
        JButton btnConfirm = new JButton("确认");
        JButton btnExit = new JButton("返回");
        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 关闭当前窗口
                SrSraverageUI.this.dispose();
            }
        });


// 添加按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(btnConfirm);
        buttonPanel.add(btnExit);




        // 添加组件到窗口
        this.add(inputPanel, BorderLayout.NORTH);
        this.add(buttonPanel, BorderLayout.CENTER);

        // 设置点击事件
        btnConfirm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedMonth = monthInputField.getText().trim();
                if (selectedMonth.isEmpty()) {
                    JOptionPane.showMessageDialog(SrSraverageUI.this,
                            "请输入要查询的月份 (格式：YYYY-MM)",
                            "提示",
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
                showStatistics(selectedMonth);
            }
        });
        setVisible(true);
    }

    /**
     * 显示某个月份的收入统计数据
     */
    private void showStatistics(String month) {
        String sql = "SELECT DATE_FORMAT(date, '%Y-%m') AS month, " +
                "SUM(spprice * spnumber) AS monthly_income " +  // 总销售额 = 单价 × 数量
                "FROM purchase_info " +
                "WHERE DATE_FORMAT(date, '%Y-%m') = ? " +
                "GROUP BY DATE_FORMAT(date, '%Y-%m')";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, month); // 设置查询参数
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                double monthlyIncome = rs.getDouble("monthly_income");
                double averageIncome = monthlyIncome / 30.0; // 平均日收入 = 月收入 ÷ 30

                // 格式化输出到控制台
                System.out.printf("月收入统计表：%n");
                System.out.println("【" + month + "】月收入统计结果");
                System.out.println("+--------+--------------+----------------+");
                System.out.println("|  月份  | 月收入(元)   | 平均日收入(元) |");
                System.out.println("+--------+--------------+----------------+");
                System.out.printf("| %-6s | %12.2f | %14.2f |\n", month, monthlyIncome, averageIncome);
                System.out.println("+--------+--------------+----------------+");

                // 弹窗显示结果
                String message = String.format(
                        "【%s】月收入统计结果\n\n月收入：%.2f 元\n平均日收入：%.2f 元",
                        month, monthlyIncome, averageIncome);

                JOptionPane.showMessageDialog(this, message, "统计信息", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "未找到该月份的收入数据", "提示", JOptionPane.INFORMATION_MESSAGE);
            }

        } catch (SQLException ex) {
            System.err.println("数据库操作失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(this,
                    "数据库操作失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SrSraverageUI ui = new SrSraverageUI();
            ui.setVisible(true);
        });
    }
}